/**
 * @project heima-leadnews
 * @author MECHREVO
 * @date 2024/1/11 15:08:56
 * @version 1.0
 */
package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.Mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {
    /**
     * app端登录
     *
     * @param loginDto
     * @return
     */

    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult loginAuth(LoginDto loginDto) {

        //判断是否是游客
        if (StringUtils.isEmpty(loginDto.getPhone()) && StringUtils.isEmpty(loginDto.getPassword())) {
            String token = AppJwtUtil.getToken(0);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("token", token);
            return ResponseResult.okResult(hashMap);
        } else {
            //根据用户查询用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = Wrappers
                    .<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, loginDto.getPhone());
            //ApUser apUser=getOne(queryWrapper);
            ApUser apUser = apUserMapper.selectOne(queryWrapper);
            //用户校验
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ACCOUNT_PASSWORD_ERROR);
            }
            //校验密码：里面是密码＋盐
            String inPutPasswordwithMd5 = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());
            if (inPutPasswordwithMd5.equals(apUser.getPassword())) {
                //比较成功返回token
                String token = AppJwtUtil.getToken(apUser.getId());
                HashMap<String, Object> hashMap = new HashMap<>();
                apUser.setPassword(null);
                apUser.setSalt(null);
                hashMap.put("token", token);
                hashMap.put("user", apUser);
                return ResponseResult.okResult(hashMap);
            } else {
                //比较失败，返回错误信息提示
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ACCOUNT_PASSWORD_ERROR);
            }
        }
    }
}
